package com.shd.edanpei.ui.fragment;

import android.app.AlertDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.shd.edanpei.R;
import com.shd.edanpei.bean.ProjectDataBean;
import com.shd.edanpei.bean.ServerPhoneBean;
import com.shd.edanpei.common.Constant;
import com.shd.edanpei.ui.activity.CertificationActivity;
import com.shd.edanpei.ui.activity.InvivationActivity;
import com.shd.edanpei.ui.activity.MyTeamActivity;
import com.shd.edanpei.ui.activity.TeamActivity;
import com.shd.edanpei.ui.activity.WebEdpMallActivity;
import com.shd.edanpei.ui.adapter.MenuAdapter;
import com.shd.edanpei.base.BaseFragment;
import com.shd.edanpei.base.StateBean;
import com.shd.edanpei.base.dialog.DialogUtil;
import com.shd.edanpei.base.network.api.ApiCreator;
import com.shd.edanpei.base.network.rx.BaseObserver;
import com.shd.edanpei.base.network.rx.RxTransformer;
import com.shd.edanpei.bean.MenuModel;
import com.shd.edanpei.bean.UserBean;
import com.shd.edanpei.bean.UserModel;
import com.shd.edanpei.presenter.contract.MineContract;
import com.shd.edanpei.db.DaoManager;
import com.shd.edanpei.enums.RoleEnum;
import com.shd.edanpei.image.LoadImageCtrl;
import com.shd.edanpei.presenter.MinePresenter;
import com.shd.edanpei.ui.activity.ALLMessageActivity;
import com.shd.edanpei.ui.activity.AccountActivity;
import com.shd.edanpei.ui.activity.ContactsActivity;
import com.shd.edanpei.ui.activity.OpinionActivity;
import com.shd.edanpei.ui.activity.SettingsActivity;
import com.shd.edanpei.ui.activity.UserInfoActivity;
import com.shd.edanpei.ui.dialog.OnKeyShareDialog;
import com.shd.edanpei.util.ToastUtil;

import butterknife.BindView;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import io.reactivex.android.schedulers.AndroidSchedulers;

import static android.content.Context.CLIPBOARD_SERVICE;

/**
 * Created by mc on 2018/9/19.
 * 我的
 */

@SuppressWarnings("ALL")
public class MineFragment extends BaseFragment<MinePresenter> implements MineContract.MineIView {

    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_camp)
    TextView tvCamp;
    @BindView(R.id.tv_role)
    TextView tvRole;
    @BindView(R.id.tv_info)
    TextView tvInfo;
    @BindView(R.id.iv_head)
    CircleImageView ivHead;
    @BindView(R.id.ll_take_number)
    View llTakeNumber;
    @BindView(R.id.tv_type)
    TextView tvType;
    @BindView(R.id.tv_take_number)
    TextView tvTakeNumber;

    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    @BindView(R.id.iv_setting)
    ImageView ivMessage;

    private MenuAdapter mAdapter;
    private ClipboardManager mClipboardManager;

    @Override
    protected Object setLayout() {
        return R.layout.fragment_mine;
    }

    @Override
    protected MinePresenter bindPresenter() {
        return new MinePresenter(this);
    }

    @Override
    protected void initView(@Nullable View view, @Nullable Bundle savedInstanceState) {
        loadImageCtrl = new LoadImageCtrl(this);
        mAdapter = new MenuAdapter(getContext(), R.layout.item_mine_menu);
        recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 3));
        recyclerView.setAdapter(mAdapter);
        mAdapter.setNewData(MenuModel.getMineMenuList(0));
        mClipboardManager = (ClipboardManager) getActivity().getSystemService(CLIPBOARD_SERVICE);
        getData();
        getUnRead();
        initData();
    }


    public void getUnRead() {
        ApiCreator.getApi().notRead()
                .compose(RxTransformer.<StateBean>errorHandle())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<StateBean>() {
                    @Override
                    protected void onSuccess(StateBean data) {
                        mAdapter.setNewData(MenuModel.getMineMenuList(data.getNewMessageNotReadNum()));

                    }
                });



    }



    @OnClick(R.id.iv_setting)
    void onMessage() {
//        startActivity(MessageActivity.class);
        startActivity(SettingsActivity.class);
    }

    private void initData() {
        UserBean userBean = DaoManager.getInstance().getUserBean();
        tvRole.setText("("+RoleEnum.getIntro(userBean.getRoleType())+")");
        if(userBean.getIsReal()){
            tvName.setText("您好 "+userBean.getRealName());
           // tvCamp.setVisibility(userBean.getTeamName().isEmpty()?View.GONE:View.VISIBLE);
            String teamName=userBean.getTeamName().isEmpty()?"您还未加入团队":userBean.getTeamName();
            tvCamp.setText(teamName+" "+"("+RoleEnum.getIntro(userBean.getRoleType())+")");
        }
        if (userBean.getRoleType() == RoleEnum.bank.getId()) {
            llTakeNumber.setVisibility(View.VISIBLE);
            tvTakeNumber.setText(userBean.getReceiptCode());
           // tvInfo.setText(userBean.getCompanyName());
            tvCamp.setVisibility(userBean.getCompanyName().isEmpty()?View.GONE:View.VISIBLE);
            tvCamp.setText(userBean.getCompanyName()+" "+"("+RoleEnum.getIntro(userBean.getRoleType())+")");
        } else if (userBean.getRoleType() == RoleEnum.boss.getId()) {
            tvType.setText("团队码");
            llTakeNumber.setVisibility(View.VISIBLE);
            tvTakeNumber.setText(userBean.getTeamCode());
            if (!TextUtils.isEmpty(userBean.getTeamCode())){
                tvCamp.setVisibility(userBean.getTeamName().isEmpty()?View.GONE:View.VISIBLE);
                tvCamp.setText(userBean.getTeamName()+" "+"("+RoleEnum.getIntro(userBean.getRoleType())+")");
            }
        } else{
            if (!TextUtils.isEmpty(userBean.getTeamCode())){
                //tvInfo.setText(userBean.getTeamName());
            }

        }



        if (!TextUtils.isEmpty(userBean.getAvatarUrl())) {
            loadImageCtrl.getGlide().load(userBean.getAvatarUrl()).into(ivHead);
            getImageViewSize(ivHead);

        }

    }

    private void getImageViewSize(ImageView imageView) {

        Drawable drawable = imageView.getDrawable();
        if (drawable != null) {
            BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
            Bitmap bitmap = bitmapDrawable.getBitmap();
        }


    }


    @Override
    protected void initListener() {
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                switch (mAdapter.getItem(position).getId()) {
                    case 1:
                        startActivity(AccountActivity.class);
                        break;
                    case 2:
                        //意见反馈
                        startActivity(OpinionActivity.class);

                        break;
                    case 3:
                        //通讯录
                        startActivity(ContactsActivity.class);
                        break;
                    case 4:
                        //消息
                        startActivity(ALLMessageActivity.class);

                        break;
                    case 5:
                        ApiCreator.getApi().getReg()
                                .compose(RxTransformer.<ProjectDataBean>errorHandle())
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe(new BaseObserver<ProjectDataBean>() {
                                    @Override
                                    protected void onSuccess(ProjectDataBean model) {
                                        //setData(model.getContent());
                                        //toShare(model);
                                        OnKeyShareDialog dialog = new OnKeyShareDialog(getContext(),null,model);
                                        dialog.show();
                                    }

                                    @Override
                                    public void onFinish() {
                                        //  ToastUtil.showToast("服务器异常!");
                                    }
                                });


                        break;
                    case 6:

                        //联系客服
                        DialogUtil.callService(getContext());
                        break;
                    case 7:
                        //我的团队
                        int roleType = DaoManager.getInstance().getUserBean().getRoleType();
                        //是否实名认证
                        if (DaoManager.getInstance().getUserBean().getIsReal()) {
                            //已认证
                            if (roleType == RoleEnum.boss.getId()) {
                                startActivity(MyTeamActivity.class);
                            } else {
                                startActivity(TeamActivity.class);
                            }
                        } else {
                            //未实名认证
                            AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
                            builder.setTitle(getString(R.string.unauthenticated))
                                    .setMessage("很抱歉，您还未实名认证，实名认证后方可查看。")
                                    .setNegativeButton(getString(R.string.cancel), null)
                                    .setPositiveButton(getString(R.string.to_authentication), new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            Bundle bundle = new Bundle();
                                            bundle.putInt(Constant.FROM, CertificationActivity.FORM_DATA);
                                            startActivity(CertificationActivity.class, bundle);
                                        }
                                    }).show();

                        }

                        break;
                    case 8:
                        Bundle bundle = new Bundle();
                        bundle.putInt(Constant.FROM, CertificationActivity.FORM_DATA);
                        startActivity(WebEdpMallActivity.class,bundle);
                        break;
                    case 9:
                        startActivity(InvivationActivity.class);
                        break;
                    default:
                        break;
                }
            }
        });
    }

    @OnClick(R.id.iv_head)
    void onHead() {
        ActivityOptionsCompat compat = ActivityOptionsCompat.makeSceneTransitionAnimation(getActivity(), ivHead, "imageHead");
        ActivityCompat.startActivity(getActivity(), new Intent(getActivity(), UserInfoActivity.class), compat.toBundle());
        // startActivity(UserInfoActivity.class);
    }
    @OnClick(R.id.rl_copy)
    void copy(){
        // 获取系统剪贴板
        // 创建一个剪贴数据集，包含一个普通文本数据条目（需要复制的数据）
        ClipData clipData = ClipData.newPlainText(null, tvTakeNumber.getText().toString());
        // 把数据集设置（复制）到剪贴板
        mClipboardManager.setPrimaryClip(clipData);
        ToastUtil.showToast("复制成功");

    }

    @Override
    public void onResume() {
        super.onResume();
        getUnRead();
        initData();
    }

    private void getData() {
        ApiCreator.getApi().getUser(DaoManager.getInstance().getUserBean().getId())
                .compose(RxTransformer.<UserModel>errorHandle())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<UserModel>() {
                    @Override
                    protected void onSuccess(UserModel model) {
                        DaoManager.getInstance().setReceiptCode(model.getReceiptCode());
                        initData();
                    }

                    @Override
                    public void onFinish() {
                    }
                });

        ApiCreator.getApi().getServerPhone()
                .compose(RxTransformer.<ServerPhoneBean>errorHandle())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<ServerPhoneBean>() {
                    @Override
                    protected void onSuccess(ServerPhoneBean data) {
                        DaoManager.getInstance().setServcePhone(data.getCompanyServerPhone());
                    }
                });
    }
    private void toShare(final ProjectDataBean model){
        ApiCreator.getApi().getProject("share_info")
                .compose(RxTransformer.<ProjectDataBean>errorHandle())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<ProjectDataBean>() {
                    @Override
                    protected void onSuccess(ProjectDataBean dataBean) {
                        OnKeyShareDialog dialog = new OnKeyShareDialog(getContext(),dataBean.getValues(),model);
                        dialog.show();
                    }

                    @Override
                    public void onFinish() {
                      //  ToastUtil.showToast("服务器异常!");
                    }
                });
    }
}

